package com.alibaba.citrus.cr.mn.order.center.facade.function.impl;

import com.alibaba.citrus.cr.common.util.ThreadPoolUtil;
import com.alibaba.citrus.cr.mn.order.center.common.SetOrderTag;
import com.alibaba.citrus.cr.mn.order.center.common.util.StopWatchUtils;
import com.alibaba.citrus.cr.mn.order.center.facade.function.check.AbstractOrderParamsCheckService;
import com.alibaba.citrus.cr.mn.order.center.facade.function.check.ExchangeOrderSubmitParamsCheck;
import com.alibaba.citrus.cr.mn.order.center.facade.function.common.AbstractOrderAtomSubmitService;
import com.alibaba.citrus.cr.mn.order.center.facade.function.convert.BeanConverter;
import com.alibaba.citrus.cr.mn.order.center.facade.function.dataobject.AtomOrderDO;
import com.alibaba.citrus.cr.mn.order.center.facade.repository.AtomOrderRepository;
import com.alibaba.cz.base.tool.log.Log;
import com.epoch.app.crb2btradecenter.domain.orderline.model.OrderLine;
import com.epoch.app.crb2btradecenter.enums.OrderStatus;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;

/**
 * @author dongju
 * @ClassName ExchangeOrderAtomSubmitServiceImpl
 * @description: 批量提交换货订单服务
 * @date 2023/05/21
 * @version: 1.0
 */
@Service("exchangeOrderAtomSubmitService")
public class ExchangeOrderAtomSubmitServiceImpl extends AbstractOrderAtomSubmitService {
    private static final Log log = Log.getLogger(ExchangeOrderAtomSubmitServiceImpl.class);

    @Resource
    private AtomOrderRepository atomOrderRepository;
    @Resource
    private ExchangeOrderSubmitParamsCheck exchangeOrderSubmitParamsCheck;

    @Override
    public String getOrderTag() {
        return SetOrderTag.EXCHANGE;
    }

    @Override
    public AbstractOrderParamsCheckService getCheckService() {
        return exchangeOrderSubmitParamsCheck;
    }

    @Override
    public void submitUpdateTransactional(List<AtomOrderDO> orderSubmitList) {
        StopWatchUtils.start(CORE_STOP_WATCH_SEQ, "submitUpdateTransactional");
        List<AtomOrderDO> atomOrderDOS = Optional.ofNullable(orderSubmitList).orElse(Lists.newArrayList());
        if (CollectionUtils.isEmpty(atomOrderDOS)) {
            return;
        }

        CountDownLatch countDownLatch = new CountDownLatch(atomOrderDOS.size());
        atomOrderDOS.forEach(orderSDO -> ThreadPoolUtil.execute(() -> {
            try {
                List<OrderLine> orderLines = orderSDO.getOrderLines();
                if (OrderStatus.BEFORE_SUBMIT.getCode().equals(orderSDO.getOrder().getStatus())) {
                    // 待提交状态的换货单，需要补充退货行
                    List<OrderLine> returnLines = new ArrayList<>(orderLines.size());
                    orderLines.forEach(line -> {
                        OrderLine returnLine = BeanConverter.convert(line, new OrderLine());
                        returnLine.setId(null);
                        // 清空退货行发货仓信息
                        clearShippingWarehouse(returnLine);

                        returnLine.setOrderLineTag(SetOrderTag.RETURN);
                        returnLine.setSerialNumber(String.valueOf(Integer.parseInt(line.getSerialNumber()) + 1));
                        returnLine.setStatus(OrderStatus.PUSHING.getCode());

                        returnLines.add(returnLine);
                    });
                    orderLines.addAll(returnLines);
                }

                for (OrderLine orderLine : orderLines) {
                    orderLine.setStatus(OrderStatus.PUSHING.getCode());

                    if (SetOrderTag.EXCHANGE.equals(orderLine.getOrderLineTag())) {
                        // 清空换货行收货仓信息
                        clearReceiveWarehouse(orderLine);
                    }
                }
                orderSDO.setOrderLines(orderLines);
                orderSDO.getOrder().setStatus(OrderStatus.PUSHING.getCode());
                atomOrderRepository.updateOrderStatus(orderSDO);
            } finally {
                countDownLatch.countDown();
            }
        }));

        try {
            countDownLatch.await();
        } catch (Exception e) {
            log.error("ExchangeOrderAtomSubmitService#submitSaveTransactional await error", e);
        }
        StopWatchUtils.stop();
    }

    private void clearShippingWarehouse(OrderLine orderLine) {
        orderLine.setShippingWarehouseOutCode("");
        orderLine.setShippingWarehouseCode("");
        orderLine.setShippingWarehouseName("");
        orderLine.setDeliveryFactoryCode("");
        orderLine.setDeliveryFactoryName("");
        orderLine.setStockCode("");
        orderLine.setStockName("");
    }

    private void clearReceiveWarehouse(OrderLine orderLine) {
        orderLine.setReceiveWarehouseOutCode("");
        orderLine.setReceiveWarehouseCode("");
        orderLine.setReceiveWarehouseName("");
        orderLine.setReceiveFactoryCode("");
        orderLine.setReceiveFactoryName("");
        orderLine.setReceiveStockCode("");
        orderLine.setReceiveStockName("");
    }
}
